<?php
/**
 * 我的商城
 *
 * @好商城 (c) 2015-2018 33HAO Inc. (http://www.33hao.com)
 * @license    http://www.33 hao.c om
 * @link       交流群号：138182377
 * @since      好商城提供技术支持 授权请购买shopnc授权
 */


defined('In33hao') or exit('Access Invalid!');

class member_indexControl extends mobileMemberControl
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 我的商城
     */
    public function indexOp()
    {
        $member_info = array();
        $member_info['available_predeposit'] = $this->member_info['available_predeposit'];
        $member_info['user_name'] = $this->member_info['member_name'];
        $member_info['member_points'] = $this->member_info['member_points'];
        $member_info['avatar'] = getMemberAvatarForID($this->member_info['member_id']);
        $member_gradeinfo = Model('member')->getOneMemberGrade(intval($this->member_info['member_exppoints']));
        $member_info['level_name'] = $member_gradeinfo['level_name'];
        $member_info['favorites_store'] = Model('favorites')->getStoreFavoritesCountByMemberId($this->member_info['member_id']);
        $member_info['favorites_goods'] = Model('favorites')->getGoodsFavoritesCountByMemberId($this->member_info['member_id']);
        $area = explode(' ', $this->member_info['member_areainfo']);
        $member_info['area'] = $area[2];
        // 交易提醒
        $model_order = Model('order');
        $member_info['order_nopay_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'NewCount');
        $member_info['order_noreceipt_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'SendCount');
        $member_info['order_notakes_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'TakesCount');
        $member_info['order_noeval_count'] = $model_order->getOrderCountByID('buyer', $this->member_info['member_id'], 'EvalCount');

        // 售前退款
        $condition = array();
        $condition['buyer_id'] = $this->member_info['member_id'];
        $condition['refund_state'] = array('lt', 3);
        $member_info['return'] = Model('refund_return')->getRefundReturnCount($condition);
        $model = Model();
        $store_info = $model->table('store')->where(['member_id' => $this->member_info['member_id']])->find();
        $member_info['store_id'] = $store_info['store_id'] ? $store_info['store_id'] : 0;
        $member_info['store_class'] = $store_info['store_class'] ? $store_info['store_class'] : 0;
        $res = $model->table('agent')->field('id')->where(['member_id' => $this->member_info['member_id']])->find();
        $member_info['agent_id'] = $res['id'] ? $res['id'] : 0;
        output_data(array('member_info' => $member_info));
    }

    /**
     * 我的推广
     */
    public function myPromotion1Op()
    {
        $model_mb_user_token = Model('mb_user_token');
        $key = $_POST['key'];
        if (empty($key)) {
            $key = $_GET['key'];
        }
        $mb_user_token_info = $model_mb_user_token->getMbUserTokenInfoByToken($key);
        output_data(array('member_info' => $mb_user_token_info));
    }

    /**
     * 我的资产
     */
    public function my_assetOp()
    {
        $param = $_GET;
        $fields_arr = array('point', 'predepoit', 'available_predeposit', 'available_rc_balance', 'redpacket', 'voucher', 'brokerage');
        $fields_str = trim($param['fields']);
        if ($fields_str) {
            $fields_arr = explode(',', $fields_str);
        }
        $member_info = array();
        if (in_array('point', $fields_arr)) {
            $member_info['point'] = $this->member_info['member_points'];
        }
        if (in_array('predepoit', $fields_arr)) {
            $member_info['predepoit'] = $this->member_info['available_predeposit'];
        }
        if (in_array('available_predeposit', $fields_arr)) {
            $member_info['available_predeposit'] = $this->member_info['available_predeposit'];
            $member_info['freeze_predeposit'] = $this->member_info['freeze_predeposit'];
        }
        if (in_array('available_rc_balance', $fields_arr)) {
            $member_info['available_rc_balance'] = $this->member_info['available_rc_balance'];
        }
        if (in_array('brokerage', $fields_arr)) {
            $member_info['brokerage'] = $this->member_info['brokerage'];
        }
        if (in_array('redpacket', $fields_arr)) {
            $member_info['redpacket'] = Model('redpacket')->getCurrentAvailableRedpacketCount($this->member_info['member_id']);
        }
        if (in_array('voucher', $fields_arr)) {
            $member_info['voucher'] = Model('voucher')->getCurrentAvailableVoucherCount($this->member_info['member_id']);
        }
        output_data($member_info);
    }

    /**
     * 积分转账首页
     */
    public function get_pointOp()
    {
        $member_info['member_points'] = $this->member_info['member_points'];
        $member_info['user_name'] = $this->member_info['member_name'];
        output_data($member_info);
    }

    /**
     * 积分转账处理
     */
    public function transfer_pointOp()
    {
        // 接收数据
        $account = $_POST['account'];
        $point = (int)$_POST['points'];

        // 判断积分是否为正整数
        if ($point < 0) {
            $res = array(
                'code' => 400,
                'msg' => "转账积分必须大于0",
            );
            output_data($res);
            die;
        }

        // 验证处理
        if (empty($account)) {
            $res = array(
                'code' => 400,
                'msg' => "收款账号不为空",
            );
            output_data($res);
            die;
        }
        if (!preg_match('/^1(3[0-9]|5[012356789]|8[0256789]|7[0678])\d{8}$/', $account, $arr)) {
            $res = array(
                'code' => 400,
                'msg' => "收款账号格式不正确",
            );
            output_data($res);
            die;
        }
        if (empty($point)) {
            $res = array(
                'code' => 400,
                'msg' => "转账积分不能为零",
            );
            output_data($res);
            die;
        }

        if ($point > $this->member_info['member_points']) {
            $res = array(
                'code' => 400,
                'msg' => "转账积分不能超过已有积分",
            );
            output_data($res);
            die;
        }
        // 查询指定账号是否存在
        $res = Model('member')->getMemberInfo(array('member_mobile' => $account));
        if (empty($res)) {
            $res = array(
                'code' => 400,
                'msg' => "转账账号不存在",
            );
            output_data($res);
            die;
        }

        // 转账处理
        $my_member_id = $this->member_info['member_id'];

        $updata['member_points'] = intval($res['member_points']) + intval($point);
        $res1 = Model('member')->editMember(array('member_id' => $res['member_id']), $updata);
        if ($res1) {
            $myupdata['member_points'] = intval($this->member_info['member_points']) - intval($point);
            Model('member')->editMember(array('member_id' => $this->member_info['member_id']), $myupdata);
        }
        // 写入记录
        $res_id = $this->writeLogs($my_member_id, $res['member_id'], $account, $point);
        $result = array(
            "code" => 200,
            'id' => $res_id,
            'msg' => '转账成功'
        );
        output_data($result);
    }

    /**
     * 积分转账记录
     */
    public function transfer_point_logOp()
    {
        if ($_POST['id']) {
            $where['id'] = $_POST['id'];
            $log = $this->get_pointLogList($where);
            output_data(array('log' => $log));
            die;
        }
        $time = getLastTimeArea(date('Y'), date('m'), 4, $_GET['curpage']);
        $where['transfer_form_id'] = $this->member_info['member_id'];
        $log_list = [];
        foreach ($time as $v) {
            $where['transfer_time'] = ['between', $v['timeArea']];
            $log['data'] = $this->get_pointLogList($where);
            foreach ($log['data'] as $key => $value) {
                $log['data'][$key]['transfer_time'] = date("Y-m-d", $value['transfer_time']);
            }

            $log['time'] = $v['date'];
            $log_list[] = $log;
        }
        output_data(array("log_list" => $log_list));
    }

    /**
     * @param $transfer_form_id 转账人id
     * @param $transfer_to_id 转账指定id
     * @param $point 转账积分
     */
    protected function writeLogs($transfer_form_id, $transfer_to_id, $account, $point)
    {
        $logDatas = array();
        $logDatas['transfer_form_id'] = $transfer_form_id;
        $logDatas['transfer_accept_id'] = $transfer_to_id;
        $logDatas['points'] = $point;
        $logDatas['account'] = $account;
        $logDatas['transfer_time'] = time();
        $res_id = Model('transfer_point_log')->insert($logDatas);
        return $res_id;
    }

    // 根据条件查询
    protected function get_pointLogList($condition)
    {
        $reslute = Model('transfer_point_log')->where($condition)->select();
        return $reslute;
    }

    // 获取卡号信息
    public function card_infoOp()
    {
        $condition['member_id'] = $this->member_info['member_id'];
        $data = Model('member_card')->where($condition)->select();
        if ($data) {
            output_data(array('card_info' => $data));
        } else {
            output_data(0);
        }
    }

    // 修改卡号
    public function edit_cardOp()
    {
        // 接收数据
        $name = $_POST['name'];
        $card_num = $_POST['card_num'];
        $bank_account = $_POST['bank_account'];
        $branch_account = $_POST['branch_account'];
        $tel = $_POST['tel'];
        $isedit = $_POST['isedit'];

        if ($name == '' || $card_num == '' || $bank_account == '' || $branch_account == '' || $tel == '') {
            $res = array(
                "code" => 400,
                "msg" => "卡号信息不能为空"
            );
            output_data($res);
            die;
        }
        if (!preg_match('/^\d{16}|\d{19}$/', $card_num, $arr)) {
            $res = array(
                'code' => 400,
                'msg' => "银行卡格式不正确",
            );
            output_data($res);
            die;
        }

        if (!preg_match('/^1(3[0-9]|5[012356789]|8[0256789]|7[0678])\d{8}$/', $tel, $arr)) {
            $res = array(
                'code' => 400,
                'msg' => "手机号格式不正确",
            );
            output_data($res);
            die;
        }

        // 准备数据
        $data['member_id'] = $this->member_info['member_id'];
        $data['member_name'] = $name;
        $data['card_num'] = $card_num;
        $data['card_bank_account'] = $bank_account;
        $data['card_branch_account'] = $branch_account;
        $data['bank_bind_mobile'] = $tel;
        if ($isedit) {
            $res = Model('member_card')->where(array("member_id" => $this->member_info['member_id']))->update($data);
        } else {
            // 写入数据库
            $res = Model("member_card")->insert($data);
        }
        if ($res) {
            $res = array(
                'code' => 200,
                'msg' => "银行卡修改成功",
            );
            output_data($res);
        }
    }

    // 得到预存款
    public function get_predepositOp()
    {
        if ($_POST['form'] == 'member') {
            $member_info['available_predeposit'] = $this->member_info['available_predeposit'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if ($_POST['form'] == 'store') {
            $member_info['available_predeposit'] = $this->member_info['av_store_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if ($_POST['form'] == 'tuiguang') {
            $member_info['available_predeposit'] = $this->member_info['av_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if ($_POST['form'] == 'agent_pt') {
            $member_info['available_predeposit'] = $this->member_info['av_agent_pt_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if ($_POST['form'] == 'agent_sq') {
            $member_info['available_predeposit'] = $this->member_info['av_agent_sq_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        if ($_POST['form'] == 'sq') {
            $member_info['available_predeposit'] = $this->member_info['av_sq_brokerage'];
            $member_info['user_name'] = $this->member_info['member_name'];
        }
        output_data($member_info);
    }

    // 代理商搜索
    public function agent_seachOp()
    {
        $addressArr = trim($_GET['address']);
        $type = trim($_GET['type']);
        $model = Model();
        if ($_GET['page']) {
            $page = $_GET['page'];
        } else {
            $page = 1;
        }
        $pagenum = 30;
        $startlimit = ($page - 1) * $pagenum;
        $where['area_info'] = array('like', "%" . $addressArr . "%");
        $where['type'] = $type;
        $server_list = $model->table('agent')->where($where)->limit("$startlimit,$pagenum")->select();
        output_data(array('server_list' => $server_list));
    }

    public function shopOp()
    {
        $log_list = [];
        $where['ob_store_id'] = $_SESSION['store_id'];
        $log['data'] = Model("ag_bill")->where($where)->select();
        $log_list[] = $log;
        output_data(array("log_list" => $log_list));
    }

    public function businessOp()
    {
        $log_list = [];
        $where['ob_store_id'] = $_SESSION['store_id'];
        $log['data'] = Model("sq_bill")->where($where)->select();
        foreach ($log['data'] as $k => $v) {
            $log['data'][$k]['ob_month'] = date('Y年m月', strtotime($v['os_month'] . "01"));
            $log['data'][$k]['month'] = date('n月', strtotime($v['os_month'] . "01"));
            $log['data'][$k]['ob_create_time'] = date('Y-m-d', $v['ob_create_date']);
        }
        $log_list[] = $log;
        output_data(array("log_list" => $log_list));
    }

    // 代理商详情
    public function agent_infoOp()
    {
        $where['member_id'] = $_GET['agent_id'];
        $data['agent'] = Model('agent')->where($where)->find();
        $data['member'] = Model('member')->where($where)->find();
        output_data(array('data' => $data));
    }

    /**
     * 提现申请
     */
    public function do_withdrawalOp()
    {
        $arr = [
            'member' => ['type' => 'available_predeposit', 'change_type' => 'cash_apply'],
            'tuiguang' => ['type' => 'av_brokerage', 'change_type' => 'fx_hy_cash'],
            'store' => ['type' => 'av_store_brokerage', 'change_type' => 'fx_store_cash'],
            'agent_pt' => ['type' => 'av_agent_pt_brokerage', 'change_type' => 'agent_pt_cash'],
            'agent_sq' => ['type' => 'av_agent_sq_brokerage', 'change_type' => 'agent_sq_cash'],
            'sq' => ['type' => 'av_sq_brokerage', 'change_type' => 'agent_sq'],
        ];
        if (!isset($arr[$_POST['op']])) {
            output_data(['code' => 400, 'msg' => "参数错误"]);
        }
        $moneynum = intval($_POST['moneynum']);
        if (!$moneynum) {
            output_data(['code' => 400, 'msg' => "提现金额不能为空"]);
        }
        if (!preg_match('/^[0-9]*[0-9]$/', $moneynum)) {
            output_data(['code' => 400, 'msg' => "提现金额必须为数字"]);
        }
        if ($moneynum % 100 != 0) {
            output_data(['code' => 400, 'msg' => "提现金额必须为100的整数倍"]);
        }
        if ($this->member_info[$arr[$_POST['op']]['type']] < $moneynum) {
            output_data(['code' => 400, 'msg' => "提现金额不足"]);
        }
        // 余额提现检测是否绑定了银行卡
        if ($_POST['op'] == 'member') {
            $card = Model('member_card')->where(['member_id' => $this->member_info['member_id']])->find();
            if (empty($card)) {
                output_data(['code' => 401, 'msg' => "未绑定银行卡"]);
            }
        }
        $data['member_id'] = $this->member_info['member_id'];
        $data['member_name'] = $this->member_info['member_name'];
        $data['amount'] = $moneynum;
        $model_pd = Model('predeposit');
        $msg = '提现成功';
        $model_pd->beginTransaction();
        try {
            if ($_POST['op'] == 'member') {
                $member_data['pdc_sn'] = $model_pd->makeSn();
                $member_data['pdc_member_id'] = $this->member_info['member_id'];
                $member_data['pdc_member_name'] = $this->member_info['member_name'];
                $member_data['pdc_amount'] = $moneynum;
                $member_data['pdc_bank_name'] = $card['card_bank_account'];
                $member_data['pdc_bank_no'] = $card['card_num'];
                $member_data['pdc_bank_user'] = $card['member_name'];
                $member_data['pdc_add_time'] = time();
                $member_data['pdc_payment_state'] = 0;
                $model_pd->addPdCash($member_data);
                $data['order_sn'] = $member_data['pdc_sn'];
                $msg = '提现申请成功';
            } else {
                $this->addBrokerageLog($moneynum);
            }
            $model_pd->changePd($arr[$_POST['op']]['change_type'], $data);
            $model_pd->commit();
            output_data(['code' => 200, 'msg' => $msg]);
        } catch (Exception $e) {
            $model_pd->rollback();
            output_data(['code' => 400, 'msg' => "提现申请失败"]);
        }
    }

    public function addBrokerageLog($money)
    {
        $log['member_id'] = $this->member_info['member_id'];
        $log['tixian_id'] = 1;
        $log['money'] = $money;
        $log['type'] = 2;
        $log['description'] = '佣金提现到余额';
        $log['addtime'] = time();
        $model_log = Model('brokerage_log');
        $where['member_id'] = $log['member_id'];
        switch ($_POST['op']) {
            case 'tuiguang' :
                $model_log->addMemberLog($log);
                break;
            case 'store' :
                $store = Model('store')->getStoreInfo($where);
                if ($store) {
                    $log['store_id'] = $store['store_id'];
                }
                $model_log->addStoreLog($log);
                break;
            case 'agent_pt' :
                $agent = Model('agent')->getAgentInfo($where);
                if ($agent) {
                    $log['agent_id'] = $agent['agent_id'];
                }
                $log['category'] = 0;
                $model_log->addAgentLog($log);
                break;
            case 'agent_sq' :
                $agent = Model('agent')->getAgentInfo($where);
                if ($agent) {
                    $log['agent_id'] = $agent['agent_id'];
                }
                $log['category'] = 1;
                $model_log->addAgentLog($log);
                break;
            case 'sq' :
                $store = Model('store')->getStoreInfo($where);
                if ($store) {
                    $log['store_id'] = $store['store_id'];
                }
                $model_log->addSqLog($log);
                break;
        }
    }


    // 根据条件查询
    protected function get_withdrawLogList($condition)
    {
        $reslute = Model('cash_withdrawal_apply')->where($condition)->select();
        return $reslute;
    }

    // 提现记录
    public function cash_withdraw_logOp()
    {
        $time = getLastTimeArea(date('Y'), date('m'), 4, $_GET['curpage']);
        $model_pd = Model('predeposit');
        $model_bg = Model('brokerage_log');
        $member_id = $this->member_info['member_id'];
        $where_log['member_id'] = $member_id;
        $size = 6;
        foreach ($time as $v) {
            switch ($_POST['name']) {
                case 'member' :
                    $log_list = $model_bg->getHalfYearCashLogList($this->member_info['member_id'],$size,$_GET['curpage']);
                    break;
                case 'tuiguang' :
                    $log_list = $model_bg->getHalfYearMemberLogList($this->member_info['member_id'],$size,$_GET['curpage'],1);
                    break;
                case 'store' :
                    $store = Model('store')->getStoreInfo($where_log);
                    if ($store) {
                        $log_list = $model_bg->getHalfYearStoreLogList($store['store_id'],$size,$_GET['curpage'],1);
                    }
                    break;
                case 'agent_pt' :
                    $log_list = $model_bg->getHalfYearAgentLogList($this->member_info['member_id'],$size,$_GET['curpage'],1,'pt');
                    break;
                case 'agent_sq' :
                    $log_list = $model_bg->getHalfYearAgentLogList($this->member_info['member_id'],$size,$_GET['curpage'],1,'sq');
                    break;
                case 'sq' :
                    $store = Model('store')->getStoreInfo($where_log);
                    if ($store) {
                        $log_list = $model_bg->getHalfYearSqLogList($store['store_id'],$size,$_GET['curpage'],1);
                    }
                    break;
            }
        }
        output_data(['log_list' => $log_list]);
    }

    public function agentOp()
    {
        $member_id = $_SESSION['member_id'];
        $where['member_id'] = $member_id;
        $agent = Model('agent')->where($where)->find();
        $area_info = explode(' ', $agent['area_info']);
        $agent['agent'] = $area_info[$agent['type'] - 1];
        $agent['total'] = $this->member_info['agent_pt_brokerage'];
        $agent['av_total'] = $this->member_info['av_agent_pt_brokerage'];
        $now_date = date("Y-m-d", time());
        $date = getlastMonthDays($now_date);
        $lastMonth = date("Ym", strtotime($date['0']));
        // 获取店铺信息
        $condition['ob_store_id'] = $_SESSION['store_id'];
        $condition['os_month'] = $lastMonth;
        $lastMonth_info = Model('sq_bill')->where($condition)->field("ob_result_totals")->find();
        $agent['result_totals'] = $lastMonth_info['ob_result_totals'] ? $lastMonth_info['ob_result_totals'] : 0;
        $data['agent'] = $agent;
        output_data($data);
    }

    public function bussOp()
    {
        $member_id = $_SESSION['member_id'];
        $where['member_id'] = $member_id;
        $agent = Model('agent')->where($where)->find();
        $area_info = explode(' ', $agent['area_info']);
        $agent['agent'] = $area_info[$agent['type'] - 1];
        $agent['total'] = $this->member_info['agent_sq_brokerage'];
        $agent['av_total'] = $this->member_info['av_agent_sq_brokerage'];
        $now_date = date("Y-m-d", time());
        $date = getlastMonthDays($now_date);
        $lastMonth = date("Ym", strtotime($date['0']));
        // 获取店铺信息
        $condition['ob_store_id'] = $_SESSION['store_id'];
        $condition['os_month'] = $lastMonth;
        $lastMonth_info = Model('sq_bill')->where($condition)->field("ob_result_totals")->find();
        $agent['result_totals'] = $lastMonth_info['ob_result_totals'] ? $lastMonth_info['ob_result_totals'] : 0;
        $data['agent'] = $agent;
        output_data($data);
    }

    public function sq_brokerageOp()
    {
        $data['sq']['total'] = $this->member_info['sq_brokerage'];
        $data['sq']['av_borkerage'] = $this->member_info['av_sq_brokerage'];
        output_data($data);
    }

    public function sq_brokerageListOp()
    {
        $time = getLastTimeArea(date('Y'), date('m'), 4, $_GET['curpage']);
        $where['store_id'] = $_SESSION['store_id'];
        $log_list = [];
        foreach ($time as $v) {
            $where['addtime'] = ['between', $v['timeArea']];
            $log['data'] = $this->get_sqLogList($where);
            foreach ($log['data'] as $key => $value) {
                $log['data'][$key]['addtime'] = date("Y-m-d", $value['addtime']);
            }
            $log['time'] = $v['date'];
            $log_list[] = $log;
        }
        $data['log_list'] = $log_list;
        output_data($data);
    }

    // 根据条件查询
    protected function get_sqLogList($condition)
    {
        $reslute = Model('sq_brokerage_log')->where($condition)->select();
        return $reslute;
    }
}
